﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using GraphicLib;
namespace GraphicLib
{
    public class GrayConvertor
    {
        /// <summary>
        /// 根据传进的Bitmap返回一个灰度化的byte数组
        /// </summary>
        /// <param name="bitmap"></param>
        /// <returns></returns>
        public static byte[] GetGrayBytes(Bitmap bitmap) 
        {
            byte[] rgbValues = null;
            byte[] grayValues = null;
            if (bitmap != null)
            {
                //HiPerfTimer myTimer = new HiPerfTimer();
                //myTimer.ClearTimer();
                //myTimer.Start();
                Rectangle rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
                System.Drawing.Imaging.BitmapData bmpData = bitmap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, bitmap.PixelFormat);
                IntPtr ptr = bmpData.Scan0;
                int bytes = bitmap.Width * bitmap.Height * 3;
                rgbValues = new byte[bytes];
                grayValues = new byte[bytes / 3];
                System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);
                double colorTemp = 0;
                int j = 0;
                for (int i = 0; i < rgbValues.Length; i += 3)
                {
                    colorTemp = rgbValues[i + 2] * 0.299 + rgbValues[i + 1] * 0.587 + rgbValues[i] * 0.114;
                    //colorTemp = (rgbValues[i + 2] + rgbValues[i + 1] + rgbValues[i]) ;
                    grayValues[j++] = (byte)colorTemp;
                    //rgbValues[i] = rgbValues[i + 1] = rgbValues[i + 2] = GetDimValue(rgbValues[i]);
                }
                //System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes);
                bitmap.UnlockBits(bmpData);
                //myTimer.Stop();
                //timeBox.Text = myTimer.Duration.ToString("####.##") + " 毫秒"; 
            }
            return grayValues;
        }

        /// <summary>
        /// 得到模糊值
        /// </summary>
        /// <param name="b"></param>
        /// <returns></returns>
        private static byte GetDimValue(byte b)
        {
            if (b < 128)
                return 0;
            return 1;
        }
    }
}
